package com.leyou.upload.service.impl;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.upload.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@Service
@Slf4j
public class UploadServiceImpl implements UploadService {

    /**
     * 支持上传的文件类型
     */
    private static final List<String> CONTENT_TYPE = Arrays.asList("image/png", "image/jpeg", "image/jpg");

    @Autowired
    private FastFileStorageClient storageClient;

    @Override
    public String uploadImage(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        //校验文件类型
        String contentType = file.getContentType();
        if (!CONTENT_TYPE.contains(contentType)) {
            log.error("文件类型不合法：{}", originalFilename);
            return null;
        }

        try {
            //校验文件内容
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if(bufferedImage == null){
                log.error("文件内容不合法：{}", originalFilename);
                return null;
            }

            //保存到本地服务器
            //file.transferTo(new File("E:\\IdeaProjects\\leyou\\image\\" + originalFilename));

            //改为FastDFS上传
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);

            //返回url，进行回写
            //return "http://image.leyou.com/" + originalFilename;
            return "http://image.leyou.com/" + storePath.getFullPath();
        } catch (IOException e) {
            log.error("图片上错错误：{}", originalFilename);
            e.printStackTrace();
        }
        return null;
    }
}
